<script setup lang="ts">
import { ref, onMounted } from 'vue';
import ArticleMenu from '@/components/article-menu.vue';
import { selectArticles } from '@/api/article';
import type { ArticleInfo } from '@/types/article';
import ArchiveList from '@/views/archived/components/ArchiveList.vue';
import ArchiveStats from '@/views/archived/components/ArchiveStats.vue';
import ArchiveTimeline from '@/views/archived/components/ArchiveTimeline.vue';
import type { ArchiveItem, MonthGroup, YearGroup } from '@/types/archived';
import ArticleTopBg from '@/components/article-top-bg.vue';
import LayoutFooter from '@/components/layout-footer.vue';
import LayoutFloatingButtons from '@/components/layout-floating-buttons.vue';
import { useWebConfigStore } from '@/stores';

// 添加类型定义
interface ArticleData extends ArticleInfo {
  views: number;
  category: string;
  publishTime: string;
}

const archives = ref<ArchiveItem[]>([]);
const totalArticles = ref(0);
const totalViews = ref(0);
const totalCategories = ref(0);
const loading = ref(true);
const currentYear = ref<number | null>(null);
const categoryMap = new Map<string, number>();
const webConfigStore = useWebConfigStore();
const expandedYears = ref<number[]>([]);

// 获取文章数据并处理
const fetchArchives = async () => {
  try {
    loading.value = true;
    const { data } = await selectArticles();

    // 计算文章总数
    totalArticles.value = data.length;

    // 计算总阅读量和分类数
    (data as ArticleData[]).forEach((article: ArticleData) => {
      totalViews.value += article.views;
      if (article.category) {
        if (!categoryMap.has(article.category)) {
          categoryMap.set(article.category, 1);
        } else {
          categoryMap.set(article.category, categoryMap.get(article.category)! + 1);
        }
      }
    });

    totalCategories.value = categoryMap.size;

    // 按年月分组处理
    const groupedArticles = (data as ArticleData[]).reduce((acc: Record<string, Record<string, ArticleData[]>>, article: ArticleData) => {
      const date = new Date(article.publishTime);
      const year = date.getFullYear();
      const month = date.getMonth() + 1;

      if (!acc[year]) acc[year] = {};
      if (!acc[year][month]) acc[year][month] = [];

      acc[year][month].push(article);
      return acc;
    }, {});

    // 转换数据结构
    archives.value = Object.entries(groupedArticles)
      .map(([year, months]): YearGroup => ({
        year: parseInt(year),
        count: Object.values(months as Record<string, ArticleData[]>).flat().length,
        months: Object.entries(months as Record<string, ArticleData[]>).map(([month, articles]): MonthGroup => ({
          month: parseInt(month),
          articles: articles.sort((a: ArticleData, b: ArticleData) =>
            new Date(b.publishTime).getTime() - new Date(a.publishTime).getTime()
          )
        })).sort((a, b) => b.month - a.month)
      }))
      .sort((a, b) => b.year - a.year);

    // 设置当前年份为最新的年份
    if (archives.value.length > 0) {
      currentYear.value = archives.value[0].year;
    }
  } catch (err) {
    console.error('获取归档失败:', err);
  } finally {
    loading.value = false;
  }
};

// 滚动到指定年份
const scrollToYear = (year: number) => {
  currentYear.value = year;
  const element = document.getElementById(`year-${year}`);
  if (element) {
    const elementPosition = element.getBoundingClientRect().top;
    const offsetPosition = elementPosition + window.pageYOffset - 100; // 这里的 100 是顶部偏移量
    window.scrollTo({
      top: offsetPosition,
      behavior: 'smooth'
    });
  }
};

// 添加月份导航功能
const scrollToMonth = (year: number, month: number) => {
  currentYear.value = year;
  const element = document.getElementById(`month-${year}-${month}`);
  if (element) {
    const elementPosition = element.getBoundingClientRect().top;
    const offsetPosition = elementPosition + window.pageYOffset - 100; // 这里的 100 是顶部偏移量
    window.scrollTo({
      top: offsetPosition,
      behavior: 'smooth'
    });
  }
};

// 添加展开/收起功能
const toggleYearMonths = (year: number) => {
  const index = expandedYears.value.indexOf(year);
  if (index === -1) {
    expandedYears.value.push(year);
  } else {
    expandedYears.value.splice(index, 1);
  }
};

// 初始化时展开当前年份
onMounted(() => {
  fetchArchives().then(() => {
    if (currentYear.value) {
      expandedYears.value = [currentYear.value];
    }
  });
});
</script>
<template>
  <div class="layout-container">
    <!-- 菜单栏 -->
    <ArticleMenu />
    <ArticleTopBg
      height="600px"
      :title="webConfigStore.archiveTitle"
      :subtitles="webConfigStore.archiveSubtitle"
      :background-images="webConfigStore.parsedArchiveCarousel"
      v-motion
      :initial="{ opacity: 0, y: 50 }"
      :enter="{ opacity: 1, y: 0, transition: { duration: 800 } }"
    ></ArticleTopBg>
    <!-- 主体布局 -->
    <div class="archived-main">
      <!-- 归档内容部分 -->
      <div class="archived-detail-card box-radius"
           v-motion
           :initial="{ opacity: 0, x: -30 }"
           :enter="{
            opacity: 1,
            x: 0,
            transition: { delay: 600 }
          }">
        <ArchiveList :archives="archives" :loading="loading" />
      </div>

      <!-- 归档侧边栏 -->
      <div class="archived-side-card box-radius"
           v-motion
           :initial="{ opacity: 0, x: 30 }"
           :enter="{
            opacity: 1,
            x: 0,
            transition: { delay: 800 }
          }">
        <!-- 统计卡片 -->
        <ArchiveStats :total-articles="totalArticles" :total-categories="totalCategories" :total-views="totalViews" />
        <!-- 时间线卡片 -->
        <ArchiveTimeline :archives="archives" :current-year="currentYear" :expanded-years="expandedYears"
                         @scroll-to-year="(year) => scrollToYear(year)"
                         @scroll-to-month="(year,month) => scrollToMonth(year,month)"
                         @toggle-year="(year) => toggleYearMonths(year)"
        />
      </div>
    </div>
    <LayoutFloatingButtons />
    <LayoutFooter />
  </div>
</template>
<style scoped lang="less">
.layout-container {
  min-height: 100vh;
  display: flex;
  flex-direction: column;

  .archived-main {
    display: flex;
    width: 1161px;
    margin: 0 auto;
    padding: 92px 12px 24px;
    gap: 24px;

    .archived-detail-card {
      flex: 1;
      background-color: #fff;
      padding: 24px;
      border-radius: 12px;
      box-shadow: 0 2px 12px rgba(0, 0, 0, 0.05);
    }

    .archived-side-card {
      width: 237px;
      position: sticky;
      top: 92px;
      height: fit-content;
    }
  }
}

// 移动端响应式优化
@media (max-width: 768px) {
  .layout-container {
    .archived-main {
      width: 95%; // 设置固定宽度比例
      max-width: 600px; // 设置最大宽度
      margin: 0 auto; // 居中显示
      flex-direction: column;
      padding: 24px 0; // 移除水平内边距
      gap: 16px;

      .archived-detail-card {
        padding: 16px;
        border-radius: 8px;
        margin: 0;
      }

      .archived-side-card {
        width: 100%;
        position: static;
        margin-top: 16px;
      }
    }
  }
}

@media (max-width: 576px) {
  .layout-container {
    .archived-main {
      width: 95%; // 小屏幕下稍微减小宽度
      padding: 16px 0;
      gap: 12px;

      .archived-detail-card {
        padding: 12px;
      }

      .archived-side-card {
        margin-top: 12px;
      }
    }
  }
}

// 横屏优化
@media screen and (orientation: landscape) and (max-height: 576px) {
  .layout-container {
    .archived-main {
      padding-top: 16px;

      .archived-side-card {
        :deep(.archive-timeline) {
          max-height: 200px;
          overflow-y: auto;
        }
      }
    }
  }
}
</style>
